<template>
	<!--  委外-->
	<div class="content">
		<div class="pageSearchView">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="物料">
					<el-select v-model="searchParam.materialId" placeholder="请选择物料" filterable clearable remote
						:remote-method="remoteMethod" style="width: 300px">
						<el-option v-for="(item, index) of materiaList" :key="index" :label="item.materialName"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
					<el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">列表信息</div>
				<div class="pageTableButView">
					<el-button  type="primary"  :icon="Plus" @click="handleAdd()">新建</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
				<el-table-column type="expand">
					<template #default="props">
						<div m="4">
							<el-table ref="tableCil" border size="small" :data="props.row.children"
								header-cell-class-name="blueTableHeader" style="width: 100%;margin-left: 20px">
								<el-table-column label="序号" type="index" width="50" align="center" />
								<el-table-column prop="deliveryCodeNumber" label="出库码位数" width="180" align="center" />
								<el-table-column prop="traceabilityCodeNumber" label="追溯码位数" width="180"
									align="center" />
								<el-table-column prop="fixedValue" label="定值" align="center" width="180" />
								<el-table-column prop="transcodingType" label="转换方式" :formatter="formatTranscodingType"
									align="center" width="200" />
								<el-table-column prop="isOrNot" label="是否电镀" align="center" width="200">
									<template #default="scope">
										<div v-if="scope.row.isOrNot"> 是 </div>
										<div v-else> 否 </div>
									</template>
								</el-table-column>
								<el-table-column prop="description" label="备注" align="center" min-width="250" />
							</el-table>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="序号" align="center" width="70">
					<template #default="scope">
						<!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{ (pageSearch.current - 1) * pageSearch.pageSize
							+ scope.$index + 1 }} </template>
				</el-table-column>
				<el-table-column prop="materialName" label="物料名称" width="250" align="center" />
				<el-table-column prop="deliveryCodeLength" label="出库码长度" width="250" align="center" />
				<el-table-column prop="traceabilityCodeLength" label="追溯码长度" width="250" align="center" />
				<el-table-column prop="description" label="备注" align="center" min-width="200" />
				<el-table-column label="操作" align="center" fixed="right" width="250">
					<template #default="scope">
						<el-button type="text" size="small" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button @click="handleDel(scope.row)" text type="danger" size="small" :icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background v-model:current-page="pageSearch.current"
					v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
					layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 弹窗表单 -->
		<el-dialog v-model="showCrud" :title="crudTitle" width="95%" top="5vh">
			<el-form :model="formData" label-width="auto" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
				<el-row :gutter="10">
					<el-col :span="6">
						<el-form-item label="物料" prop="materialId">
							<el-select v-model="formData.materialId" placeholder="请选择物料" filterable clearable remote
								:remote-method="remoteMethod" style="width: 300px">
								<el-option v-for="(item, index) of materiaList" :key="index" :label="item.materialName"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="出库码长度" prop="deliveryCodeLength">
							<el-input-number v-model="formData.deliveryCodeLength" :step="1" step-strictly :min="0"
								style="width: 300px" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="追溯码长度" prop="traceabilityCodeLength">
							<el-input-number v-model="formData.traceabilityCodeLength" :step="1" step-strictly :min="0"
								style="width: 300px" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="备注" prop="description">
							<el-input v-model="formData.description" style="width: 300px" />
						</el-form-item>
					</el-col>
				</el-row>
				<div class="pageTableMenuView">
					<div class="pageTableTitle"> 物料明细 </div>
					<div class="pageTableButView">
					</div>
				</div>
				<el-table class="pageTableClass" :data="workDetailData" border row-key="id" height="400px">
					<el-table-column label="序号" align="center" type="index" width="65" />
					<el-table-column type="index" label="出库码位数" align="center" min-width="180" />
					<el-table-column prop="traceabilityCodeNumber" label="追溯码位数" align="center" min-width="180">
						<template #default="scope">
							<el-input v-model="scope.row.traceabilityCodeNumber" />
						</template>
					</el-table-column>
					<el-table-column prop="fixedValue" label="定值" align="center" min-width="180">
						<template #default="scope">
							<el-input v-model="scope.row.fixedValue" />
						</template>
					</el-table-column>
					<el-table-column prop="transcodingType" label="转换方式" align="center" width="200">
						<template #default="scope">
							<el-select v-model="scope.row.transcodingType" placeholder="请选择转换方式" clearable>
								<el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="isOrNot" label="是否电镀" align="center" width="200">
						<template #default="scope">
							<el-select v-model="scope.row.isOrNot" placeholder="请选择是否电镀" clearable>
								<el-option :key="1" label="是" :value="true" />
								<el-option :key="0" label="否" :value="false" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="description" label="备注" align="center" min-width="250">
						<template #default="scope">
							<el-input v-model="scope.row.description" clearable />
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" fixed="right" width="150">
						<template #header="scope">
							<el-button type="text" size="small" :icon="Plus" @click="addWorkOrderDetail">新建</el-button>
						</template>
						<template #default="scope">
							<el-button @click="delWorkOrderDetail(scope.$index)" text type="danger" size="small"
								:icon="Delete">删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
//弹出层标题
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Plus, Refresh, Search } from '@element-plus/icons-vue';

onMounted(() => {
	getList();
	getOption();
});


const pageSearch = ref({
	current: 1,
	pageSize: 10
});


const workDetailData = ref([{}]);

const addWorkOrderDetail = () => {
	workDetailData.value.push({});
};


const delWorkOrderDetail = (e) => {
	workDetailData.value.splice(e, 1);
};



const pageTotal = ref(null);//页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const crudTitle = computed(() => {
	return isEdit.value ? '编辑' : '新建';
});




const typeOptions = ref([
	{
		label: "直接取值",
		value: 0
	}, {
		label: "周转月",
		value: 1
	}, {
		label: "周和天转日",
		value: 2
	}, {
		label: "尺寸",
		value: 3
	}, {
		label: "定值",
		value: 4
	}, {
		label: "流水号",
		value: 5
	}
])

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
	materialId: any,
	deliveryCodeLength: any,
	traceabilityCodeLength: any,
	detailsList: any
}

const formData = ref({})


const rules = reactive<FormRules<RuleForm>>({
	materialId: [
		{ required: true, message: '请选择物料', trigger: 'blur' }
	],
	traceabilityCodeLength: [
		{ required: true, message: '请输入追溯码长度', trigger: 'blur' }
	],
	deliveryCodeLength: [
		{ required: true, message: '请输入出库码长度', trigger: 'blur' }
	]
});


const paginatedData = ref([])
const materiaList = ref([]);//物料表

const getOption = () => {
	axiosInstance
		.post('/api/basedata/material/getPage', {
			current: 1,
			pageSize: 20
		}).then(res => {
			if (res.code == 200) {
				materiaList.value = res.data.records;
			}
		});

};

const remoteMethod = (query: string) => {
	if (query) {
		axiosInstance
			.post('/api/basedata/material/getPage', {
				current: 1,
				pageSize: 20,
				materialName: query
			}).then(res => {
				if (res.code == 200) {
					materiaList.value = res.data.records;
				}
			});
	}

}

const formatTranscodingType = (value: any) => {
	return typeOptions.value.find(item => item.value == value.transcodingType).label
}


// 获取列表接口
const getList = () => {
	axiosInstance.post('/api/outboundTranscodingRules/getPage', {
		...searchParam.value,
		...pageSearch.value
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			const list = res.data.records;
			for (const item of list) {
				item.children = item.detailsList;
			}
			paginatedData.value = list;
			console.log(paginatedData.value);

			pageTotal.value = res.data.total;
		});
};

const handleSizeChange = (e: any) => {
	pageSearch.value.pageSize = e;
	getList();
};

const handleCurrentChange = (e: any) => {
	pageSearch.value.current = e;
	getList();
};

// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	pageSearch.value.current = 1;
	// current.value = 1
	getList();
};

// 点击新建
const handleAdd = () => {
	isEdit.value = false;
	formData.value = {}
	workDetailData.value = [{}];
	showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
	isEdit.value = true;
	formData.value = row
	workDetailData.value = row.detailsList
	showCrud.value = true;

};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		axiosInstance.delete(`/api/outboundTranscodingRules/delete`, {
			data: {
				ids: [row.id]
			}
		}).then(res => {
			ElMessage.success('删除成功');
			getList(); // 刷新数据
		});


	});
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
	if (!e) return;
	await e.validate((valid, fields) => {
		if (valid) {
			const list = workDetailData.value
			for (let i = 0; i < list.length; i++) {
				list[i].deliveryCodeNumber = i + 1
			}
			formData.value.detailsList = list

			if (isEdit.value) {
				// 编辑
				axiosInstance.put('/api/outboundTranscodingRules/update', formData.value).then(res => {
					if (res.code != 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					getList(); // 刷新数据
				});
			} else {
				// 新建
				axiosInstance.post('/api/outboundTranscodingRules/save', formData.value).then(res => {
					if (res.code != 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					getList(); // 刷新数据
				});
			}

		}
	});
};

</script>
<style scoped></style>
